package cn.wind.xboot.core.utils;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.Map;


/**
 * @author Exrickx
 */
@Slf4j
public class IpInfoUtil {

    /**
     * appKey  https://market.aliyun.com/products/57002002/cmapi018957.html?spm=5176.730005.productlist.d_cmapi018957.LGNtUM#sku=yuncode1295700000
     */
    private final static String APPKEY = "ce9acb1e2b1523ff4d6efd9457193ae4";
    /** appCode*/
    private final static  String APPCODE="33bb451d61e046e78e70a4d66b03db97";

    /**
     * Mob IP查询接口
     */
    private final static String GET_IP_LOCATE = "http://iploc.market.alicloudapi.com/v3/ip?ip=";

    /**
     * 获取IP返回地理信息
     * @param ip ip地址
     * @return
     */
    public static String getIpCity(String ip){
        String result="未知";
        if("127.0.0.1".equalsIgnoreCase(ip)){
            return "本地";
        }
        if(null != ip){
            String url = GET_IP_LOCATE + ip;
            Map headers=Maps.newHashMap();
            headers.put("Authorization","APPCODE " + APPCODE);
            try{
                ResponseEntity  responseEntity=HttpClientUtil.sendGetRequest(url,null,headers );
                if(responseEntity.getStatusCode().equals(HttpStatus.OK)){
                    JSONObject jsonObject=JSONObject.parseObject(responseEntity.getBody().toString());
                    result=jsonObject.getString("city");
                }else {
                    result="获取IP信息失败";
                }
            }catch (Exception e){
                result="获取IP信息失败";
            }

        }
        return result;
    }
}
